package com.utils.basejava.concurrent.atguigu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程操作资源类
 * 判断干活通知
 * 防止虚假唤醒
 * @author XR-8
 * AA打印 1次   BB打印2次  CC打印3次
 * 再从AA开始，循环5次
 */

class ConditionData{
	private int status = 1;
	private Lock lock = new ReentrantLock();
	private Condition condition1 = lock.newCondition();
	private Condition condition2 = lock.newCondition();
	private Condition condition3 = lock.newCondition();
	
	public void print1() throws InterruptedException {
		lock.lock();
		try {
			while(status!=1) {
				condition1.await();
			}
			for (int i = 0; i < 1; i++) {
				System.out.println(Thread.currentThread().getName()+"\t"+"打印1次");
			}
			status = 2;
			condition2.signal();
		} finally {
			lock.unlock();
		}
	}
	
	public void print2() throws InterruptedException {
		lock.lock();
		try {
			while(status!=2) {
				condition2.await();
			}
			for (int i = 0; i < 2; i++) {
				System.out.println(Thread.currentThread().getName()+"\t"+"打印2次");
			}
			status = 3;
			condition3.signal();
		} finally {
			lock.unlock();
		}
	}
	
	public void print3() throws InterruptedException {
		lock.lock();
		try {
			while(status!=3) {
				condition3.await();
			}
			for (int i = 0; i < 3; i++) {
				System.out.println(Thread.currentThread().getName()+"\t"+"打印3次");
			}
			status = 1;
			condition1.signal();
		} finally {
			lock.unlock();
		}
	}
}


public class MoreConditionDemo {
	public static void main(String[] args) {
		ConditionData conditionData = new ConditionData();
		new Thread(()->{
			for (int i = 0; i < 5; i++) {
				try {
					conditionData.print1();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"AAA").start();
		
		new Thread(()->{
			for (int i = 0; i < 5; i++) {
				try {
					conditionData.print2();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"BBB").start();
		
		new Thread(()->{
			for (int i = 0; i < 5; i++) {
				try {
					conditionData.print3();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"CCC").start();
		
	}

}
